package com.stxx.stiot2.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import org.noear.liquor.DynamicCompiler;
import org.noear.solon.annotation.Component;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class JavaUtils {
    public final static DynamicCompiler compiler = new DynamicCompiler();
    public static Object getClassInstance(String classCode){
            String className = "Dc"+DigestUtil.md5Hex16(classCode.replaceAll("/\\*(?:.|[\\n\\r])*?\\*/", "")
                .replaceAll("//.*", "")
                .replaceAll("[\\p{Cntrl}\\s]", ""));
            Class<?> clazz = null;
            try {
                if(compiler.getClassLoader().getClassNames().contains(className)){
                    clazz = compiler.getClassLoader().loadClass(className);
                }else{
                    compiler.addSource(className,getClassCode(classCode,className)).build();
                    clazz = compiler.getClassLoader().loadClass(className);
                }
                Constructor<?> constructor = clazz.getDeclaredConstructor();
                return constructor.newInstance();
            } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException |
                     InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
    }

    static String getClassCode(String classCode,String className){
        Pattern pattern = Pattern.compile("(?<=\\bclass\\s)\\w+");
        Matcher matcher = pattern.matcher(classCode);
        StringBuffer sb = new StringBuffer();
        if(matcher.find()){
            matcher.appendReplacement(sb,className);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
